package com.fa4j.common.web.util;

import com.fa4j.common.base.exception.ServerException;
import org.springframework.util.ClassUtils;

import java.util.HashMap;
import java.util.Map;

public class ContextUtil {

    public static ThreadLocal<Map<String, Object>> threadLocal = ThreadLocal.withInitial(HashMap::new);


    public static void set(String key, Object value) {
        threadLocal.get().put(key, value);
    }

    public static <T> T get(String key) {
        return (T) threadLocal.get().get(key);
    }

    public static void remove(String key) {
        threadLocal.get().remove(key);
    }

    public static void removeAll() {
        threadLocal.remove();
    }

    public static void set(Object value) {
        if (value == null || ClassUtils.isPrimitiveOrWrapper(value.getClass())) {
            return;
        }
        threadLocal.get().put(value.getClass().getSimpleName(), value);
    }

    public static <T> T get(Class<T> clazz) {
        if (ClassUtils.isPrimitiveOrWrapper(clazz)) {
            throw new ServerException("该方法不支持基本类型");
        }
        return get(clazz.getSimpleName());
    }
}
